package org.jeecg.modules.leave.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.leave.entity.AgLeave;
import org.jeecg.modules.leave.service.IAgLeaveService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.workflow.utils.ProcessKit;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.CountDownLatch;

/**
 * @Description: ag_leave
 * @Author: jeecg-boot
 * @Date: 2020-05-18
 * @Version: V1.0
 */
@Api(tags = "ag_leave")
@RestController
@RequestMapping("/leave/agLeave")
@Slf4j
public class AgLeaveController extends JeecgController<AgLeave, IAgLeaveService> {
    @Autowired
    private IAgLeaveService agLeaveService;

    @Autowired
    private ISysUserService sysUserService;

    @PutMapping(value = "/justEdit")
    public Result<?> justEdit(@RequestBody AgLeave agLeave) {
        if(agLeave.getId() != null) {
            if(!agLeaveService.removeById(agLeave.getId()))
                return Result.error(agLeave.getXujbh() + "; 删除历史数据失败");
        }

        log.info("请假开始>>>>>>>>>>>>>>>>>>>>");
        agLeave.setId(null);
        agLeave.setStatus(0);
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        agLeave.setFirstAudit(agLeave.getAuditing());
        log.info("审批人>>>>>>>>>>>>>>>>>>>>"+agLeave.getAuditing());

        String[] applyers = StringUtils.split(agLeave.getApplyer(),",");
        if(null != applyers && applyers.length>0){
            log.info("1>>>>>>>>>>>>>>>>>>>>");

            CountDownLatch latch = new CountDownLatch(applyers.length);
            for(String applyer:applyers){
                log.info("2>>>>>>>>>>>>>>>>>>>>");

                AgLeave l = new AgLeave();
                BeanUtils.copyProperties(agLeave,l);
                new Thread(()->{
                    try{
                        log.info("3>>>>>>>>>>>>>>>>>>>>");

                        String applicant = agLeave.getApplicant();
                        System.out.println(applicant);
                        l.setId(null);
                        l.setApplicant(applyer);
                        l.setOrgCode(queryOrgCodeByUserName(applyer));
                        agLeaveService.save(l);
                        agLeaveService.startFlow(l, loginUser);
                    }finally {
                        latch.countDown();
                        log.info("4>>>>>>>>>>>>>>>>>>>>");
                    }
                }).start();
                log.info("5>>>>>>>>>>>>>>>>>>>>");
            }
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return Result.ok("添加成功！");
    }

    @GetMapping(value = "/xiaojia")
    public Result<?> xiaojia(String id) {
        AgLeave agLeave = agLeaveService.getById(id);
        if(agLeave != null) {
            agLeave.setXiaojTime(new Date());
            agLeave.setStatus(2);

            agLeaveService.updateById(agLeave);
            return Result.ok();
        }

        return Result.error("销假失败");
    }

    @GetMapping(value = "/mytodolist4xiaoj")
    public Result<?> mytodolist4xiaoj(AgLeave agLeave,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {
        Page<AgLeave> page = new Page<AgLeave>(pageNo, pageSize);

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<AgLeave> pageList = agLeaveService.page(page, new QueryWrapper<AgLeave>()
//                .eq("auditing", user.getUsername())
//                .isNull("xiaoj_time")
                .eq("status", "1"));

//        IPage<AgLeave> iPage = agLeaveService.myTodoTasks(page, user, agLeave);
//        Iterator<AgLeave> itor = iPage.getRecords().iterator();
//        while (itor.hasNext()) {
//            AgLeave agLeave1 = itor.next();
//            if(!agLeave1.getTaskName().equals("学员返校直接领导销假"))
//                itor.remove();
//        }

        return Result.ok(pageList);
    }

    @GetMapping(value = "/myapplylist")
    public Result<?> myApplyList(AgLeave agLeave,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req) {

        Page<AgLeave> page = new Page<AgLeave>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<AgLeave> iPage = agLeaveService.myApplyList(page, user, agLeave);
        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(record -> {
                if (null != record.getEndTime()) {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                } else {
                    if (null != record.getAuditStatus()) {
                        if(record.getAuditStatus().equals("0"))
                            record.setProcessStatus(ProcessKit.FLOW_STATUS_REJECT);

                        if(record.getAuditStatus().equals("1"))
                            record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);

                    } else {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
                    }
                }
            });
        }
        return Result.ok(iPage);
    }

    @GetMapping(value = "/mytodolist")
    public Result<?> myTodoList(AgLeave agLeave,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {
        Page<AgLeave> page = new Page<AgLeave>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        IPage<AgLeave> iPage = agLeaveService.myTodoTasks(page, user, agLeave);
        return Result.ok(iPage);
    }

    @GetMapping(value = "/mydonelist")
    public Result<?> myDoneList(AgLeave hqCggl,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {
        Page<AgLeave> page = new Page<AgLeave>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        IPage<AgLeave> iPage = agLeaveService.myDoneTasks(page, user, hqCggl);
        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(record -> {
                if (null != record.getEndTime()) {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                } else {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                }
            });
        }
        return Result.ok(page);
    }

    @GetMapping("/runWhere")
    public void runWhere(String id, HttpServletResponse httpServletResponse) {
        try {
//			workflowService.runWhere(id, httpServletResponse);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 分页列表查询
     *
     * @param agLeave
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ag_leave-分页列表查询")
    @ApiOperation(value = "ag_leave-分页列表查询", notes = "ag_leave-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AgLeave agLeave,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        Map reqMap = req.getParameterMap();
        QueryWrapper<AgLeave> queryWrapper = QueryGenerator.initQueryWrapper(agLeave, reqMap);
        queryWrapper.eq("applicant", ((LoginUser) SecurityUtils.getSubject().getPrincipal()).getId());
        Page<AgLeave> page = new Page<AgLeave>(pageNo, pageSize);
        IPage<AgLeave> pageList = agLeaveService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    String queryOrgCodeByUserName(String userName) {
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", userName), false);
        if(sysUser != null)
            return sysUser.getOrgCode();

        return null;
    }


    /**
     * 添加
     *
     * @param agLeave
     * @return
     */
    @AutoLog(value = "ag_leave-添加")
    @ApiOperation(value = "ag_leave-添加", notes = "ag_leave-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AgLeave agLeave) {
        log.info("请假开始>>>>>>>>>>>>>>>>>>>>");
        agLeave.setStatus(0);
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        agLeave.setFirstAudit(agLeave.getAuditing());
        log.info("审批人>>>>>>>>>>>>>>>>>>>>"+agLeave.getAuditing());

        String[] applyers = StringUtils.split(agLeave.getApplyer(),",");
        if(null != applyers && applyers.length>0){
            log.info("1>>>>>>>>>>>>>>>>>>>>");

            CountDownLatch latch = new CountDownLatch(applyers.length);
            for(String applyer:applyers){
                log.info("2>>>>>>>>>>>>>>>>>>>>");

                AgLeave l = new AgLeave();
                BeanUtils.copyProperties(agLeave,l);
                new Thread(()->{
                    try{
                        log.info("3>>>>>>>>>>>>>>>>>>>>");

                        String applicant = agLeave.getApplicant();
                        System.out.println(applicant);
                        l.setId(null);
                        l.setApplicant(applyer);
                        l.setOrgCode(queryOrgCodeByUserName(applyer));
                        agLeaveService.save(l);
                        agLeaveService.startFlow(l, loginUser);
                    }finally {
                        latch.countDown();
                        log.info("4>>>>>>>>>>>>>>>>>>>>");
                    }
                }).start();
                log.info("5>>>>>>>>>>>>>>>>>>>>");
            }
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param agLeave
     * @return
     */
    @AutoLog(value = "ag_leave-编辑")
    @ApiOperation(value = "ag_leave-编辑", notes = "ag_leave-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody AgLeave agLeave) {
        agLeave.setStatus(1);
//		agLeaveService.updateById(agLeave);
        agLeaveService.applyAgin(agLeave);
        return Result.ok("提交成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ag_leave-通过id删除")
    @ApiOperation(value = "ag_leave-通过id删除", notes = "ag_leave-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        agLeaveService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ag_leave-批量删除")
    @ApiOperation(value = "ag_leave-批量删除", notes = "ag_leave-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.agLeaveService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ag_leave-通过id查询")
    @ApiOperation(value = "ag_leave-通过id查询", notes = "ag_leave-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AgLeave agLeave = agLeaveService.getById(id);
        if (agLeave == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(agLeave);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param agLeave
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AgLeave agLeave) {
        return super.exportXls(request, agLeave, AgLeave.class, "ag_leave");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AgLeave.class);
    }

    @AutoLog(value = "ag_leave-任务列表")
    @ApiOperation(value = "ag_leave-任务列表", notes = "ag_leave-任务列表")
    @GetMapping(value = "/tasklist")
    public Result<?> taskList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roles = sysUserService.getRole(loginUser.getUsername());
        IPage<AgLeave> page = agLeaveService.taskList(roles, pageNo, pageSize);

        return Result.ok(page);
    }

    @AutoLog(value = "ag_leave-任务审批")
    @ApiOperation(value = "ag_leave-任务审批", notes = "ag_leave-任务审批")
    @PostMapping(value = "/completetask")
    public Result<?> completeTask(@RequestBody Map params) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        agLeaveService.complateTask(loginUser, (String) params.get("taskId"), (Integer) params.get("auditStatus"),
                (String) params.get("memo"), (Integer) params.get("go2xiaoj"), (String) params.get("auditUser"));

        return Result.ok("操作成功");
    }

    @PostMapping("/batchcompletetask")
    public Result<?> batchCompleteTask(@RequestBody List<Map> paramsList) {
        paramsList.forEach(params -> {
            AgLeave agLeave = agLeaveService.getById(params.get("id") + "");
            if(agLeave != null) {
                agLeave.setXiaojTime(new Date());
                agLeave.setStatus(2);

                agLeaveService.updateById(agLeave);
            }
        });

        return Result.ok("操作成功");
    }

    @AutoLog(value = "ag_leave-重新申请")
    @ApiOperation(value = "ag_leave-重新申请", notes = "ag_leave-重新申请")
    @PostMapping(value = "/applyagin")
    public Result<?> applyAgin(@RequestBody Map params) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        agLeaveService.complateTask(loginUser, (String) params.get("taskId"), (Integer) params.get("auditStatus"),
                (String) params.get("memo"), null, null);

        return Result.ok("操作成功");
    }
}
